package com.lglbc.day1;

import java.io.FileInputStream;
import java.lang.reflect.Method;

/**
 * @Description TODO
 * @Author 乐哥聊编程
 * @Date 2022/11/14 21:04
 */
public class MyClassLoader extends ClassLoader{
    private String classPath = "/Users/neil/Desktop/code/training-code/jvm/target";
    private byte[] loadByte(String name) throws Exception {
        name = name.replaceAll("\\.", "/");
        FileInputStream fis = new FileInputStream(classPath + "/" + name
                + ".class");
        int len = fis.available();
        byte[] data = new byte[len];
        fis.read(data);
        fis.close();
        return data;
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        return super.loadClass(name, resolve);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] data = loadByte(name);
            return defineClass(name, data, 0, data.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ClassNotFoundException();
        }
    }

    public static void main(String args[]) throws Exception {
        MyClassLoader classLoader = new MyClassLoader();
        Class clazz = classLoader.loadClass("com.lglbc.UserService");
        Object obj = clazz.newInstance();
        Method method = clazz.getDeclaredMethod("print", null);
        method.invoke(obj, null);
        System.out.println("MyClassLoader 被"+MyClassLoader.class.getClassLoader()+"加载");
    }
}